<template>
    <div id="PlacesView">
        <a-card title="景点信息" style="width: 100%" :bordered="false" :hoverable="true">
            <template #extra>
                <a-button type="link" @click="gotoSpotAdmin">more</a-button>
            </template>
            <a-table :columns="columns" :data-source="data" :scroll="{ x: 400, y: 580 }" :custom-row="handleRowClick">
                <template #headerCell="{ column }">
                    <template v-if="column.key === 'name'">
                        <span style="color: #1890ff">Name</span>
                    </template>
                </template>
                <template #customFilterDropdown="{ setSelectedKeys, selectedKeys, confirm, clearFilters, column }">
                    <div style="padding: 8px">
                        <!-- 搜索输入框 -->
                        <a-input ref="searchInput" :placeholder="`Search ${column.dataIndex}`" :value="selectedKeys[0]"
                            style="width: 188px; margin-bottom: 8px; display: block"
                            @change="e => setSelectedKeys(e.target.value ? [e.target.value] : [])"
                            @pressEnter="handleSearch(selectedKeys, confirm, column.dataIndex)" />
                        <!-- 操作按钮 -->
                        <a-button type="primary" size="small" style="width: 90px; margin-right: 8px"
                            @click="handleSearch(selectedKeys, confirm, column.dataIndex)">
                            <template #icon>
                                <SearchOutlined />
                            </template>
                            Search
                        </a-button>
                        <a-button size="small" style="width: 90px" @click="handleReset(clearFilters)">
                            Reset
                        </a-button>
                    </div>
                </template>
                <!-- 自定义过滤图标样式，提供视觉反馈。 -->
                <template #customFilterIcon="{ filtered }">
                    <search-outlined :style="{ color: filtered ? '#108ee9' : undefined }" />
                </template>
                <!-- 自定义表格单元格内容，高亮显示匹配搜索关键词的部分。 -->
                <template #bodyCell="{ text, column, record }">
                    <span v-if="state.searchText && state.searchedColumn === column.dataIndex">
                        <template v-for="(fragment, i) in text
                            .toString()
                            .split(new RegExp(`(?<=${state.searchText})|(?=${state.searchText})`, 'i'))">
                            <mark v-if="fragment.toLowerCase() === state.searchText.toLowerCase()" :key="i"
                                class="highlight">
                                {{ fragment }}
                            </mark>
                            <template v-else>{{ fragment }}</template>
                        </template>
                    </span>
                    <!-- <template v-if="column.key === 'name'">
                        {{ record.name }}
                    </template> -->
                    <template v-else-if="column.key === 'tags'">
                        <span>
                            <a-tag v-for="tag in record.tags" :key="tag"
                                :color="tag === 'loser' ? 'volcano' : tag.length > 5 ? 'geekblue' : 'green'">
                                {{ tag.toUpperCase() }}
                            </a-tag>
                        </span>
                    </template>
                    <template v-else-if="column.key === 'photo'">
                        <a-image :src=record.photo />
                    </template>
                    <template v-else-if="column.key === 'rating'">
                        <a-rate v-model:value=record.rating allow-half />
                    </template>
                </template>
            </a-table>
        </a-card>
    </div>
</template>

<script setup>
import { watch, ref, onMounted, reactive } from 'vue';
import { spotsInfoStore } from '@/stores/spots';
import { SearchOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import { useRouter } from 'vue-router';

const router = useRouter()
const onChange = (pagination, filters, sorter) => {
    console.log('params', pagination, filters, sorter);
};
const spotsStore = spotsInfoStore();
let beforetemp = spotsStore.tempData;
const data = ref([]);

//搜索相关变量
const state = reactive({
    searchText: '',
    searchedColumn: '',
});
const searchInput = ref();

const columns = ref([
    {
        title: 'Name',
        dataIndex: 'name',
        key: 'name',
        width: 100,
        fixed: 'left',
        customFilterDropdown: true,
        onFilter: (value, record) => record.name.toString().toLowerCase().includes(value.toLowerCase()),
        onFilterDropdownOpenChange: visible => {
            if (visible) {
                setTimeout(() => {
                    searchInput.value.focus();
                }, 100);
            }
        },
    },
    {
        title: 'Address',
        dataIndex: 'address',
        width: 100,
        key: 'address',
    },
    {
        title: 'Tags',
        key: 'tags',
        width: 100,
        dataIndex: 'tags',
    },
    {
        title: 'Rating',
        key: 'rating',
        width: 150,
        dataIndex: 'rating',
    },
    {
        title: 'Comment',
        key: 'comment',
        width: 100,
        dataIndex: 'comment'
    },
    {
        title: 'Photo',
        key: 'photo',
        width: 100,
        dataIndex: 'photo',
    },
])
// 更新景点信息
const updatePlaces = (citydata) => {
    const updatedData = [];
    for (let i = 0; i < citydata.length; i++) {
        updatedData.push({
            key: i + 1,
            photo: citydata[i].photos[0],
            name: citydata[i].spotname,
            address: citydata[i].address,
            tags: citydata[i].type.split(/[;|]/),
            rating: citydata[i].rating,
            tel: citydata[i].tel,
            comment: citydata[i].comment,
            cityname: JSON.parse(localStorage.getItem('cityData')),
            location: citydata[i].location,
        });
    }
    data.value = updatedData;
};
//路由跳转事件
const gotoSpotAdmin = () => {
    router.push('/spotsAdmin')
}

// 处理行点击事件
const handleRowClick = (record) => {
    return {
        onClick: () => {
            spotsStore.SetSelectedSpot(record);
            // console.log(spotsStore.selectedSpot);

        }
    };
};

// 搜索相关方法
const handleSearch = (selectedKeys, confirm, dataIndex) => {
    confirm();
    if (selectedKeys.length === 0) {
        message.error('请输入搜索内容');
        return;
    }
    console.log(beforetemp.filter((item) => item.spotname.includes(selectedKeys[0])));

    if (beforetemp.filter((item) => item.spotname.includes(selectedKeys[0])).length === 0) {
        message.error('未找到相关景点');
        return;
    }
    console.log(selectedKeys, dataIndex);
    state.searchText = selectedKeys[0];
    state.searchedColumn = dataIndex;
    beforetemp = spotsStore.tempData
    // 地图上的景点信息更新
    spotsStore.SetcityData(spotsStore.cityData.filter((item) => item.spotname.includes(selectedKeys[0])));
    console.log(spotsStore.cityData, 'spotsStore.cityData', beforetemp, 'temp');

};
const handleReset = clearFilters => {
    clearFilters({
        confirm: true,
    });
    state.searchText = '';
    console.log(beforetemp, 'temp');
    spotsStore.SetcityData(spotsStore.tempData);
    console.log(spotsStore.cityData, 'spotsStore.cityData');
};

// Lifecycle hook
onMounted(() => {
    updatePlaces(spotsStore.cityData);
});

watch(() => spotsStore.cityData, (newCityData) => {
    updatePlaces(newCityData);
    // console.log(newCityData, 'spotsStore.cityData');
}, { deep: true });
</script>

<style scoped>
#PlacesView {
    width: 100%;
    height: 100%;
}

.highlight {
    background-color: rgb(255, 192, 105);
    padding: 0px;
}
</style>